﻿namespace FiftyOne.Foundation.Mobile.Detection.Wurfl.Matchers.ReducedInitialString
{
    using FiftyOne.Foundation.Mobile.Detection.Wurfl;
    using FiftyOne.Foundation.Mobile.Detection.Wurfl.Handlers;
    using FiftyOne.Foundation.Mobile.Detection.Wurfl.Matchers;
    using System;

    internal class Matcher
    {
        private static void Check(string userAgent, ref DeviceInfo bestMatch, ref int maxInitialString, DeviceInfo current)
        {
            if ((userAgent.StartsWith(current.UserAgent) || current.UserAgent.StartsWith(userAgent)) && (maxInitialString < current.UserAgent.Length))
            {
                maxInitialString = current.UserAgent.Length;
                bestMatch = current;
            }
        }

        internal static Results Match(string userAgent, Handler handler, int tolerance)
        {
            DeviceInfo bestMatch = null;
            int maxInitialString = 0;
            lock (handler.UserAgents)
            {
                foreach (DeviceInfo[] infoArray in handler.UserAgents)
                {
                    foreach (DeviceInfo info2 in infoArray)
                    {
                        Check(userAgent, ref bestMatch, ref maxInitialString, info2);
                    }
                }
            }
            if (maxInitialString >= tolerance)
            {
                return new Results(bestMatch);
            }
            return null;
        }
    }
}

